package com.visionet.school.app.web.web;

import com.alibaba.fastjson.JSONObject;
import com.visionet.school.app.web.common.utils.PageInfo;
import com.visionet.school.app.web.common.web.WebContextFactory;
import com.visionet.school.app.web.entity.enums.MemberFileType;
import com.visionet.school.app.web.entity.enums.MemberType;
import com.visionet.school.app.web.entity.file.vo.FileVo;
import com.visionet.school.app.web.entity.member.Member;
import com.visionet.school.app.web.entity.member.MemberRel;
import com.visionet.school.app.web.entity.vo.LoginAccountVo;
import com.visionet.school.app.web.entity.vo.MemberVo;
import com.visionet.school.app.web.entity.vo.StudentVo;
import com.visionet.school.app.web.service.file.FileClassService;
import com.visionet.school.app.web.service.member.MemberRelService;
import com.visionet.school.app.web.service.member.MemberService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by hxpeng on 2017/3/3.
 */
@Controller
@RequestMapping("/member")
public class MemberController{

    private static final Logger logger = LoggerFactory.getLogger(MemberController.class);

    @Autowired
    private MemberService memberService;

    @Autowired
    private FileClassService fileClassService;

    @Autowired
    private MemberRelService memberRelService;


    /**
     * pc   成员列表
     * @param memberVo
     * @return
     */
    @RequestMapping(value = "/getMemberPage", method = RequestMethod.POST)
    public ResponseEntity<?> getMemberPage(@RequestBody MemberVo memberVo){
        if(memberVo.getPageInfo() == null){
            memberVo.setPageInfo(new PageInfo());
        }
        Map<String,Object> map = new HashMap<>();
        try {
            map.put("pageResult",memberService.getMemberPage(memberVo,"createDate"));
        }catch (Exception e){
            e.printStackTrace();
            map.put("stat","err");
        }
        return new ResponseEntity(map , HttpStatus.OK);
    }

    /**
     * pc   获取成员信息(ID,类别)
     * @param memberVo
     * @return
     */
    @RequestMapping(value = "/getMemberInfo", method = RequestMethod.POST)
    public ResponseEntity<?> getMemberInfo(@RequestBody MemberVo memberVo){
        if(memberVo == null || StringUtils.isBlank(memberVo.getId())){
            return new ResponseEntity(null , HttpStatus.BAD_REQUEST);
        }
        Map<String,Object> map = new HashMap<>();
        map.put("memberInfo",memberService.getMemberInfo(memberVo.getId()));
        return new ResponseEntity(map , HttpStatus.OK);
    }

    /**
     * wechat   获取成员家长信息
     * @param memberVo
     * @return
     */
    @RequestMapping(value = "/getParentInfo", method = RequestMethod.POST)
    public ResponseEntity<?> getParentInfo(@RequestBody MemberVo memberVo){
        if(memberVo == null || StringUtils.isBlank(memberVo.getId())){
            return new ResponseEntity(null , HttpStatus.BAD_REQUEST);
        }
        Map<String,Object> map = new HashMap<>();
        map.put("memberList",memberService.getParentInfo(memberVo.getId()));
        return new ResponseEntity(map , HttpStatus.OK);
    }

    /**
     * pc   查询所有学生
     * @param memberVo
     * @return
     */
    @RequestMapping(value = "/queryStudent", method = RequestMethod.POST)
    public ResponseEntity<?> queryStudent(@RequestBody MemberVo memberVo){
        Map<String,Object> map = new HashMap<>();
        try{
            map.put("pageResult", memberService.queryStudent(memberVo));
        }catch (Exception e){
            e.printStackTrace();
            map.put("stat","err");
        }
        return new ResponseEntity(map , HttpStatus.OK);
    }

    /**
     * pc   查询所有老师
     * @param memberVo
     * @return
     */
    @RequestMapping(value = "/queryTeacher", method = RequestMethod.POST)
    public ResponseEntity<?> queryTeacher(@RequestBody MemberVo memberVo){
        Map<String,Object> map = new HashMap<>();
        try{
            map.put("queryTeacher", memberService.queryTeacher(memberVo));
        }catch (Exception e){
            e.printStackTrace();
            map.put("stat","err");
        }
        return new ResponseEntity(map , HttpStatus.OK);
    }

    /**
     * pc   添加学生班级
     * @param memberVo
     * @return
     */
    @RequestMapping(value = "/insertStudentClass", method = RequestMethod.POST)
    public ResponseEntity<?> insertStudentClass(@RequestBody MemberVo memberVo){
        if(memberVo == null || StringUtils.isBlank(memberVo.getClassId()) || StringUtils.isBlank(memberVo.getMemberId())){
            return new ResponseEntity(null , HttpStatus.BAD_REQUEST);
        }
        Map<String,String> map = new HashMap<>();
        try {
            memberService.insertStudentClass(memberVo);
            map.put("stat","success");
        }catch (Exception e){
            e.printStackTrace();
            map.put("stat","err");
            map.put("msg",e.getMessage());
        }
        return new ResponseEntity(map , HttpStatus.OK);
    }

    /**
     * pc   删除学生
     * @param id
     */
    @RequestMapping(value = "/deleteStudent", method = RequestMethod.GET)
    public ResponseEntity<?>  deleteStudent(String id){
        long start = System.currentTimeMillis();
        if(StringUtils.isBlank(id)){
            return new ResponseEntity(null , HttpStatus.BAD_REQUEST);
        }
        Map<String,String> map = new HashMap<>();
        try {
            memberService.deleteStudent(id);
            map.put("stat","success");
        }catch (Exception e){
            map.put("stat","err");
//            map.put("msg",e.getMessage());
        }
        long end=System.currentTimeMillis();
        System.out.println("删除一条学生执行时间：" + (end-start) + "ms");
        return new ResponseEntity(map , HttpStatus.OK);
    }

    /**
     * wechat   保存家长信息入口
     * @param memberVo
     * @return
     */
    @RequestMapping(value = "/saveParentMemberInfo", method = RequestMethod.POST)
    public ResponseEntity<?> saveMemberInfo(@RequestBody MemberVo memberVo){
        if(memberVo == null || StringUtils.isBlank(memberVo.getId()) || StringUtils.isBlank(memberVo.getMemberType())){
            return new ResponseEntity(null , HttpStatus.BAD_REQUEST);
        }
        Map<String,Object> map = new HashMap<>();
        Member member = memberService.saveMemberInfo(memberVo);
        if(member == null){
            map.put("result","failed");
        }else{
            map.put("result","success");
            map.put("memberInfo",member);
        }
        return new ResponseEntity(map , HttpStatus.OK);
    }

    /**
     * PC   保存成员信息
     * @param memberVo
     * @return
     */
    @RequestMapping(value = "/pcSaveMemberInfo", method = RequestMethod.POST)
    public ResponseEntity<?> pcSaveMemberInfo(@RequestBody MemberVo memberVo){
        Map<String,Object> map = new HashMap<>();
        try {
            memberService.pcSaveMemberInfo(memberVo);
            map.put("stat", "success");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new ResponseEntity(map , HttpStatus.OK);
    }

    /**
     * wechat   查找一个学生
     * @param memberVo
     * @return
     */
    @RequestMapping(value = "/findOneStudent", method = RequestMethod.POST)
    public ResponseEntity<?> findOneStudent(@RequestBody MemberVo memberVo){
        if(memberVo == null || StringUtils.isBlank(memberVo.getStudentNumber()) || StringUtils.isBlank(memberVo.getMemberName())){
            return new ResponseEntity(null , HttpStatus.BAD_REQUEST);
        }
        HashMap<String,Object> map = new HashMap<>();
        map.put("student",memberService.findStudentByNumberAndName(memberVo));
        return new ResponseEntity(map , HttpStatus.OK);
    }



    /**
     * wechat   微信用户和成员/班级绑定
     * @param memberVo
     * @return
     */
    @RequestMapping(value = "/bindWeChatInfo", method = RequestMethod.POST)
    public ResponseEntity<?> bindWeChatInfo(@RequestBody MemberVo memberVo){
        if(memberVo == null){
            return new ResponseEntity(null , HttpStatus.BAD_REQUEST);
        }
        HashMap<String,Object> map = new HashMap<>();
        try {
            String memberType = memberVo.getMemberType();
            if(StringUtils.isBlank(memberVo.getOpenId()) || StringUtils.isBlank(memberVo.getMemberName()) || StringUtils.isBlank(memberVo.getMemberPhone())){
                throw new NullPointerException("参数为空！");
            }
            if(memberType.equals(MemberType.TEACHER.toKey())){
                if(StringUtils.isBlank(memberVo.getClassName())){
                    throw new NullPointerException("参数为空！");
                }
            }else if(memberType.equals(MemberType.PARENT.toKey())){
                if(StringUtils.isBlank(memberVo.getStudentNumber()) || StringUtils.isBlank(memberVo.getStudentName()) || StringUtils.isBlank(memberVo.getMemberRelType())){
                    throw new NullPointerException("参数为空！");
                }
            }
            LoginAccountVo loginAccountVo = memberService.bindWeChatInfo(memberVo);
            WebContextFactory.getWebContext().setLoginAccountVo(loginAccountVo);
            map.put("stat","success");
            map.put("loginAccountVo",loginAccountVo);
        }catch (Exception e){
            map.put("stat","err");
            map.put("msg",e.getMessage());
        }
        return new ResponseEntity(map , HttpStatus.OK);
    }

    /**
     * wechat   下载微信临时素材（精彩瞬间）
     * @param jsonObject
     * @return
     */
    @RequestMapping(value = "/submitUploadImg", method = RequestMethod.POST)
    public ResponseEntity<?> bindWeChatInfo(@RequestBody JSONObject jsonObject){
        String serverIds = jsonObject.getString("serverIds");
        Map<String,Object> map = new HashMap<>();
        if(StringUtils.isNotBlank(serverIds)){
            try {
                List<String> list = JSONObject.parseArray(serverIds,String.class);
                if(list != null && list.size() > 0){
                    List<FileVo> fileList = memberService.downLoadWechatImg(list);
                    map.put("stat","success");
                    map.put("fileList",fileList);
                }else{
                    map.put("stat","null");
                }
            }catch (Exception e){
                map.put("stat","err");
                map.put("msg",e.getMessage());
                e.printStackTrace();
            }
        }
        return new ResponseEntity(map, HttpStatus.OK);
    }

    /**
     * wechat   查找班级精彩瞬间
     * @param fileVo
     * @return
     */
    @RequestMapping(value = "/queryStudentsPhoto", method = RequestMethod.POST)
    public ResponseEntity<?> queryStudentsPhoto(@RequestBody FileVo fileVo){
        if(fileVo == null){
            return new ResponseEntity(null , HttpStatus.BAD_REQUEST);
        }
        if(fileVo.getPageInfo() == null){
            fileVo.setPageInfo(new PageInfo());
        }

        LoginAccountVo loginAccountVo = WebContextFactory.getWebContext().getLoginAccountVo();
        List<String> memberIds = new ArrayList<>();
        memberIds.add(loginAccountVo.getMemberId());
        for(StudentVo s : loginAccountVo.getStudentVoList()){
            memberIds.add(s.getMemberId());
        }
        fileVo.setMemberIds(memberIds);

        Map<String,Object> map = new HashMap<>();
        try {
            fileVo.setMemberFileType(MemberFileType.ALBUM.toKey());
            map.put("classPhoto", fileClassService.queryStudentsPhoto(fileVo));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new ResponseEntity(map, HttpStatus.OK);
    }

    /**
     * wechat   学生是否被绑定
     * @param jsonObject
     * @return
     */
    @RequestMapping(value = "/studentHadBind", method = RequestMethod.POST)
    public ResponseEntity<?> studentHadBind(@RequestBody JSONObject jsonObject){
        if(jsonObject == null || StringUtils.isBlank(jsonObject.getString("memberId"))){
            return new ResponseEntity(null , HttpStatus.BAD_REQUEST);
        }
        Map<String,Object> map = new HashMap<>();
        try {
            int i = memberRelService.studentHadBind(jsonObject.getString("memberId"));
            if(i > 0){
                map.put("result","yse");
            }
        } catch (Exception e) {
            e.printStackTrace();
            map.put("result","err");
            map.put("msg",e.getMessage());
        }
        return new ResponseEntity(map, HttpStatus.OK);
    }

    @RequestMapping(value = "/getFamilyInfo", method = RequestMethod.POST)
    public ResponseEntity<?> getfamilyInfo(@RequestBody JSONObject jsonObject){
        String rememberId = jsonObject.getString("rememberId");
        if(StringUtils.isBlank(rememberId)){
            return new ResponseEntity(null , HttpStatus.BAD_REQUEST);
        }
        Map<String,Object> map = new HashMap<>();
        List<MemberVo> entity=memberRelService.getFamilyInfo(rememberId);
        try {
            if(entity == null){
                map.put("stat","err");
                map.put("msg","该学生还未绑定家长！");
                return new ResponseEntity(map , HttpStatus.OK);
            }
            map.put("familyInfo",entity);
        }catch (Exception e){
            e.printStackTrace();
        }
        return new ResponseEntity(map, HttpStatus.OK);
    }

    @RequestMapping(value = "/getStudentInfoByParentId", method = RequestMethod.POST)
    public ResponseEntity<?> getStudentInfoByParentId(@RequestBody JSONObject jsonObject){
        Map<String,Object> map = new HashMap<>();
        String memberId = jsonObject.getString("memberId");
        if(StringUtils.isBlank(memberId)){
            return new ResponseEntity(null , HttpStatus.BAD_REQUEST);
        }
        List<Member> memberRel = memberService.findStudentByParentId(memberId);
        map.put("studentInfo",memberRel);
        return new ResponseEntity(map , HttpStatus.OK);
    }

    @RequestMapping(value = "/changeRel",method = RequestMethod.POST)
    public ResponseEntity<?> changeRel(@RequestBody JSONObject jsonObject){
        Map<String,Object> map = new HashMap<>();
        if(jsonObject == null || StringUtils.isBlank(jsonObject.getString("relType")) || StringUtils.isBlank(jsonObject.getString("relmemberId"))){
            return new ResponseEntity(null , HttpStatus.BAD_REQUEST);
        }
        try{
            memberRelService.updateReltype(jsonObject.getString("relType"),jsonObject.getString("relmemberId"),jsonObject.getString("memberId"));
        }catch (Exception e){
            e.printStackTrace();
            map.put("result","err");
            return new ResponseEntity(null , HttpStatus.BAD_REQUEST);
        }
        map.put("result","success");
        return new ResponseEntity<Object>(map, HttpStatus.OK);
    }

//    @RequestMapping(value = "/Modify",method = RequestMethod.POST)
//    public ResponseEntity<?> modify(@RequestBody MemberVo memberVo){
//        Map<String,Object> map = new HashMap<>();
//        if(StringUtils.isEmpty(memberVo.getMemberName())&& StringUtils.isEmpty(memberVo.getMemberPhone())){
//            return new ResponseEntity(null , HttpStatus.BAD_REQUEST);
//        }
//        try {
//            memberService.modify(memberVo,memberVo.getMemberName(),memberVo.getMemberPhone());
//        }catch (Exception e){
//            e.printStackTrace();
//            map.put("result","err");
//            return new ResponseEntity(null , HttpStatus.BAD_REQUEST);
//        }
//        map.put("result","success");
//        return new ResponseEntity<Object>(map, HttpStatus.OK);
//    }
}
